package com.async.handler.impl;

import com.async.domain.entity.AsyncReq;
import com.async.enums.AsyncTypeEnum;
import com.async.enums.ExecStatusEnum;
import com.async.handler.context.AsyncStrategyContext;
import com.async.handler.impl.AbstractAsyncHandlerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
/**
 * <p>
 * 先保存到数据库再异步消息处理
 * </p>
 * @author yang
 * @date 2024/5/17
 */
@Slf4j
@Component
public class SaveAsyncHandlerService extends AbstractAsyncHandlerService {
    @Override
    public boolean execute(AsyncStrategyContext context) {
        AsyncReq asyncReq = this.saveAsyncReq(context.getAsyncExecDto(), ExecStatusEnum.INIT.getStatus());
        // 保存到数据失败
        if (asyncReq == null){
            // 降级为仅异步消息处理
            return asyncProducer.send(context.getAsyncExecDto());
        }
        // 发消息，包含数据库ID
        boolean success = asyncProducer.send(asyncConverter.toAsyncExecDto.apply(asyncReq));
        // 发送失败，更新状态为失败
        if (!success){
            asyncReqService.updateStatusAndExecCount(asyncReq.getId(), ExecStatusEnum.ERROR.getStatus());
        }
        return true;
    }

    @Override
    public List<String> listType() {
        return Collections.singletonList(AsyncTypeEnum.SAVE_ASYNC.name());
    }
}
